<?php

namespace app\api\controller;
use data\Json;
use think\Request;
use JPush\Client as JPush;
use app\common\model\ActivityCalendar;
use app\common\model\Travel as TravelModel;
use app\common\model\TravelMember;
use app\common\model\Activity;
use app\common\model\Oversea;
/**
 * 社群/用户 注册+登录+发送短信验证码
 */
class Travel extends Base
{
    protected $user_model = null;
    protected $token = null;
    protected $user = null;

    public function _initialize()
    {
        $this->user_model = model('User');
        $this->token = request()->header('token');
        //$this->user = $this->user_model->getUserInfo($this->token);
        $this->user = $this->user_model->get('18');
    }

    /**
    * DIY活动
    */
    public function diy(Request $request)
    {
        if(!$this->user)return Json::json_send(1);

        if($request->isPost())
        {
            $data = input();

            if(request()->file('poster'))
            {
                $data['poster'] = $this->upload(request()->file('poster'));
            }

            $data['sponsor'] = $this->user['id'];
            $data['diy'] = 1;
            $data['state'] = 2;
            $data['categorys'] = Activity::getCategory($data['category']);

            $vali = $this->validate($data,'Travel.diy');
            if($vali !== true) return Json::json_send($vali);

            $baidu = build_sn($data['city'].$data['address']);
            $data['longitude'] = $baidu['lng'];
            $data['latitude']  = $baidu['lat'];

            if(isset($data['travel_id']) && $data['travel_id'])
            {
                $result = model('Travel')->allowField(true)->save($data,['id'=>$data['travel_id']]);
            }
            else
            {
                $result = model('Travel')->allowField(true)->save($data);
            }

            if($result !== false)
            {
                // 生成二维码
                $qrcode = qrcode(model('Travel')->id,url('User/checkin',['travelid'=>model('Travel')->id])); 
                model('Travel')->isUpdate(true)->save(['qrcode'=>$qrcode,'id'=>model('Travel')->id]);

                // 保存相册
                /*$albums = $this->multiUpload(request()->file('images'));
                $list = [];
                foreach ($albums as $k => $v) {
                    $list[] = ['travel_id'=>model('Travel')->id,'url'=>$v];
                }
                model('TravelAlbum')->saveAll($list);*/

                // 众筹规则
                if($data['rules'])
                {
                    model('TravelRules')::where('travel_id',model('Travel')->id)->delete(true);
                    $list = [];
                    foreach (json_decode($data['rules'],true) as $k => $v)
                    {
                        $list[] = ['travel_id'=>model('Travel')->id,'min'=>$v['min'],'max'=>$v['max'],'price'=>$v['price']];
                    }
                    model('TravelRules')->saveAll($list);
                }

                return Json::json_send(0);
            }
            return Json::json_send(7);
        }
    }

    /**
    * 行程列表
    * 应用一: 活动列表
    *         场景一：全部活动（包括海内外）
    *         场景二：海外活动  type = 1
    *         场景三：国内活动分类列表 category 1=艺术沙龙,2=禅修,3= 私董会,4=游学,5=户外活动,6=课程
    * 应用二：活动管理（我发布的活动） self=1;
    *         场景一：国内  type = 0 
    *                 状态 state  0=已提交 等待审核,1=审核通过（生成活动中）；2=报名中；3=已结束,4 =审核未通过,5=已取消
    *         场景二：国外  type = 1
    *         
    * 应用三：我参加的活动【用户端】 join = 1 
    */
    public function list()
    {
        if(!$this->user)return Json::json_send(1);
        
         // 当前页数
        $page = input('page',1);

        // 首页活动列表，显示报名中的活动
        $map['state'] = 2;
        $map['titles']  = ['<>',''];

        $self = input('self',0);

        $join = input('join',0);
        // 我计划的活动
        if($self)
        {
            unset($map['state']);
            // 获取发布人id
            $map['sponsor']  = $this->user['id'];
            // 查询状态  0 已提交 等待审核；1 审核通过（生成活动中）；2 报名中；3 已结束；4 审核未通过;5 已取消
            if(!empty(input('state'))) $map['state'] = input('state');
        }

        // 我参加的活动
        if($join)
        {
            unset($map['state']);
            $travel_ids = model('TravelMember')->where(['member_id'=>$this->user['id']])->column('travel_id');
            $map['id']  = ['in',implode(',', $travel_ids)];
        }

        if(input('?type'))
        {
            $map['type'] = input('type',0);
        }

        if(input('?category'))
        {
            $category = input('category',0);
        }

        // 条件查询
        if(input('?condition'))
        {
            $map['titles|categorys|desc'] = ['like',"%".input('condition')."%"];
        }

        // 总行数
        $sumRow = TravelModel::where($map)->count();

        // 每页显示的行数
        $rowPage = config('row_page');

        // 总页数
        $sumPage = round($sumRow/$rowPage);

        $beginRow = $page <= 1 ? 0:($page-1) * $rowPage;

        $travelList = TravelModel::where($map)->order('createtime desc')->limit($beginRow,$rowPage)->select();
        $data = [];
        foreach ($travelList as $k => $v) {
            // 是否是DIY活动
            if($v['diy'])
            {
                $poster  = model('TravelAlbum')::where('travel_id',$v['id'])->find();
                $poster  = empty($poster)?"":$poster['url'];
                $address = $v['address'];
                $city    = $v['city'];
                if(isset($category) && $category == $v['category'])
                {
                    $include++;
                }
            }
            else
            {
                $type    = TravelModel::where('id',$v['id'])->value('type');
                $join    = $type == 1 ? "oversea":"activity";
                $poster  = count($v[$join])==0?'':$v[$join][0]['poster'];
                $address = count($v[$join])==0?'':$v[$join][0]['address'];
                $city    = count($v[$join])==0?'':Activity::getCity($v[$join][0]['city_id']);
                $include = 0;
                foreach ($v[$join] as $tk => $tv) {
                    if(isset($category) && $category == $tv['category'])
                    {
                        $include++;
                    }
                }

                //$activtyMap['id'] = $v['id'];
                //$activitylist = TravelModel::with($join)->where($activtyMap)->find();
            }

            
            $travelMember = model('TravelMember')->where(['travel_id'=>$v['id'],'member_id'=>$this->user['id']])->find();
            $data[$k] = [
                'id'         => $v['id'],
                'type'       => $v['type'],
                'sponsor'    => model('User')->where(['id'=>$v['sponsor']])->value('name'),
                'categorys'  => $v['categorys'],
                'titles'     => $v['titles'],
                'begintime'  => $v['begintime'],
                'endtime'    => $v['endtime'],
                'fee'        => $v['memebr_price'],
                //'poster'     => count($v[$join])==0?'':$v[$join][0]['poster'],
                //'address'    => count($v[$join])==0?'':$v[$join][0]['address'],
                //'city'       => count($v[$join])==0?'':Activity::getCity($v[$join][0]['city_id']),
                'poster'     => $poster,
                'address'    => $address,
                'city'       => $address,
                'state'      => $v['state'],//0 已提交 等待审核；1 审核通过（生成活动中）；2 报名中；3 已结束；4 审核未通过
                'is_promote' => $v['is_promote'],
                'diy'        => $v['diy'],
                'paid'       => empty($travelMember)?0:$travelMember['paid'],
            ];

            if(isset($category) && $include == 0)
            {
                unset($data[$k]);
            }
        }

        return Json::json_send(0,'',$data);
    }


    public function index(Request $request)
    {
        if(!$this->user)return Json::json_send(1);
        if($request->isPost())
        {
            $data = input();
            $data['sponsor'] = $this->user['id'];
            $data['step'] = input('step',1);
            $data['type'] = input('type',0);
            $vali = $this->validate($data,TravelModel::getScene($data['step'],$data['type']));
            if($vali !== true){
                return Json::json_send($vali);
            }

            switch ($data['step']) {
                case '1':
                    return $this->base($data);
                    break;
                case '2':
                    return $this->chooseActivity($data);
                    break;
                case '3':
                    return $this->chooseSite($data['travel_id'],$data['activity_id'],$data['site_id']);
                    break;
                case '4':
                    $type = TravelModel::where(['id'=>$data['travel_id']])->value('type');
                    if($type==1)
                    {
                        return $this->generateOverseas($data['travel_id']);
                    }
                    return $this->generateTravel($data['travel_id']);
                   // return $this->generateTravel($data['travel_id']);
                    break;
                default:
                    # code...
                    break;
            }
            return Json::json_send(7);
        }

        if(input('travel_id'))
        {
            $travel_id = input('travel_id',0);

            $dayno     = input('dayno',0);

            $type      = TravelModel::where(['id'=>$travel_id])->value('type');

            $join      = $type==1?'oversea':'activity';

            $travel    = TravelModel::with($join)->where(['id'=>$travel_id])->find();

            $data = [];
            foreach ($travel[$join] as $k => $v) {
                $date = date('Y/m/d',$v['pivot']['begintime']);
                $v['category_abbr'] = model('Activity')->getAcCategoryAbbr($v['category']);
                $address = '';
                if($v['is_site']){
                    $address   = $v['site_address'];
                    $longitude = $v['longitude'];
                    $latitude  = $v['latitude'];
                }
                else
                {
                    $site_id   = model('TravelActivity')
                                ->where(['travel_id'=>$travel_id,'activity_id'=>$v['id']])
                                ->value('site_id');
                    $siteinfo  = model('Activity')->get($site_id);
                    $address   = $siteinfo['address'];
                    $longitude = $siteinfo['longitude'];
                    $latitude  = $siteinfo['latitude'];
                }

                $activity = [
                    'id'     => $v['id'],
                    'address'=> $address,
                    'lon'    => $longitude,
                    'lat'    => $latitude
                ];

                if($dayno)
                {
                    if($dayno == $k+1)
                    {
                        $data[$k]['day'] = $v['pivot']['begintime'];
                        $data[$k]['dayno']   = $k+1;
                        $data[$k]['activties'][] = $activity;
                    }
                }
                else{
                    $data[$k]['day'] = $v['pivot']['begintime'];
                    $data[$k]['dayno']   = $k+1;
                    $data[$k]['activties'][] = $activity;
                }
            }
            return Json::json_send(0,'',$data);
        }
        
    }

    public function exit()
    {
        if(!$this->user) return Json::json_send(1);
        $travel_id = input('travel_id',0);
        if(empty($travel_id)) return Json::json_send(9);
        $result = model('TravelMember')->where(['travel_id'=>$travel_id,'member_id'=>$this->user['id']])->delete();
        if($result !== false)
        {
            // 

              // 退款

            //
            return Json::json_send(0);
        }

        return Json::json_send(9);
    }

    // 活动报名
    public function signuplist(Request $request)
    {
        if(!$this->user) return Json::json_send(1);
        $travel_id = input('travel_id',0);
        $travel = TravelModel::where(['id'=>$travel_id])->find();
        if(!$travel) return Json::json_send(4);

        if($request->isPost())
        {
            $data = input();
            if($travel['type'] == 1)
            {
                // 海外游学订单
                $payfee = $data['deposit'] = $travel['total_fee'] * (config('signup_oversea_percent')/100);
            }
            else
            {
                // 报名费用
                $payfee = $data['paid_fee'] = $travel['memebr_price'];
            }
            $data['member_id'] = $this->user['id'];
            $result = model('TravelMember')->allowField(true)->save($data);
            if($result !== false)
            {

                // 支付费用==活动定金==活动总费用*百分比
                $payfee = $travel['memebr_price'];

                // 获取支付渠道
                $channel = input('channel','ALI_APP');//"ALI_APP";

                // 获取交易密码
                $transpwd = input('transpwd','');

                // 支付验证参数
                $valiParam = [
                        'type'   => 2,// 用户类型：1供应商；2社群|用户
                        'user'   => $this->user,
                        'payfee' => $payfee,
                        'channel' => $channel,
                        'transpwd' => $transpwd
                ];

                // 支付验证
                if(valiPayment($valiParam)) return Json::json_send(valiPayment($valiParam));

                // 拼接订单参数
                $param = [
                    'good_id'   => model('TravelMember')->id,
                    'total_fee' => $payfee,
                    'title'     => $travel['titles'],
                    'channel'   => input('channel','ALI_APP'),//"ALI_APP";
                    'type'      => 1,//"ALI_APP";
                ];
                $this->redirect(url('pay/index', $param));
            }
            return Json::json_send(9);
        }

        $map['travel_id']=$travel_id;
        if(input('is_checkin'))
        {
            $map['is_checkin']=1;
        }
        $list = TravelMember::alias('tm')->join('user u','tm.member_id=u.id')
                ->field('u.avatar,u.id,u.name,u.mobile,tm.is_checkin,tm.check_time,tm.paid,tm.paid_fee,tm.other')->where($map)->order('check_time desc')->select();
        foreach ($list as $k => $v) {
            if($this->user['role'] == 1)
            {
                $communityMember = model('communityMember')->where(['community_id'=>$this->user['id'],'user_id'=>$v['id']])->find();
                $list[$k]['state'] = $communityMember['state'];
            }
            $other = [];
            if($v['other'])
            {
                $otherlist = explode(',', $v['other']);
                foreach ($otherlist as $key => $value) {
                    $info = model('TravelOther')->get($value);
                    array_push($other, ['name'=>$info['name'],'fee'=>$info['fee']]);
                }
                $list[$k]['other'] = $other;
            }  
            
        }
        return Json::json_send(0,'',$list);
    }

    // 海外游学支付尾款接口
    public function paytail(Request $request)
    {
        if(!$this->user) return Json::json_send(1);
        $travel_id = input('travel_id',0);
        $travel = TravelModel::where(['id'=>$travel_id])->find();
        if(!$travel) return Json::json_send(4);
        if($request->isPost())
        {
            $travelMember = model('TravelMember')->where(['travel_id'=>$travel_id,'member_id'=>$this->user['id']])->find();
            // 尾款
            $data['paid_fee'] = $travel['total_fee'] - $travel['total_fee']*(config('signup_oversea_percent')/100);
            $result = model('TravelMember')->allowField(true)->save($data,['id'=>$travelMember['id']]);
            if($result !== false)
            {
                // 支付费用==活动定金==活动总费用*百分比
                $payfee = $data['paid_fee'];
               // 获取支付渠道
                $channel = input('channel','ALI_APP');//"ALI_APP";

                // 获取交易密码
                $transpwd = input('transpwd','');

                // 支付验证参数
                $valiParam = [
                        'type'   => 2,// 用户类型：1供应商；2社群|用户
                        'user'   => $this->user,
                        'payfee' => $payfee,
                        'channel' => $channel,
                        'transpwd' => $transpwd
                ];

                // 支付验证
                if(valiPayment($valiParam)) return Json::json_send(valiPayment($valiParam));
            
               $param = [
                    'good_id'   => $travelMember['id'],
                    'total_fee' => $payfee,
                    'title'     => $travel['titles'],
                    'channel'   => input('channel','ALI_APP'),//"ALI_APP";
                    'type'      => 3,//"支付尾款";
                ];
                $this->redirect(url('pay/index', $param));
            }
            return Json::json_send(9);
        }
    }

    /**
    * 生成活动\报名活动\海外游学支付尾款 支付页面，显示支付订金金额、余额是否充足
    * $type == 0 发布活动支付订金
    * $type == 1 报名活动
    * $type == 2 海外报名活动支付尾款
    */
    public function payment()
    {
        if(!$this->user) return Json::json_send(1);
        $travel_id = input('travel_id',0);
        $travel = TravelModel::where(['id'=>$travel_id])->find();
        $type = input('type',0);
        // 是否购买附加产品
        $other = input('other','');
        $deposit = $type == 2?$travel['total_fee'] * (config('signup_oversea_percent')/100):0;
        switch ($type) {
            case '1':
                $pay_fee = $travel['type'] == 1? $deposit : $travel['memebr_price'];
                if($other)
                {
                    $otherArr = explode(',', $other);
                    foreach ($otherArr as $k => $v) {
                        $pay_fee += model('TravelOther')::where(['id'=>$v])->value('fee');
                    }
                }
                break;
            case '2':
                $pay_fee = $travel['total_fee'] - $deposit;
                break;
            default:
                $pay_fee = $travel['total_fee'] * (config('release_deposit_percent')/100);
                break;
        }
        $return = [
            'type'      => $type,
            'travel_id' => $travel_id,
            'pay_fee'   => $pay_fee,
            'sum_fee'   => $travel['total_fee'],
            'percent'   => config('signup_oversea_percent'),
            'paid_fee'  => $deposit,
            'is_sufficient'=> $this->user['wallet_money'] > $pay_fee ? 1:0
        ];
        return Json::json_send(0,'',$return);
    }

    // 生成活动支付定金
    public function pay()
    {
        if(!$this->user) return Json::json_send(1);
        $travel_id = input('travel_id',0);
        $travel = TravelModel::where(['id'=>$travel_id])->find();
        // 支付费用==活动定金==活动总费用*百分比
        $payfee = $travel['total_fee'] * (config('release_deposit_percent')/100);
        // 获取支付渠道
        $channel = input('channel','ALI_APP');//"ALI_APP";
        $transpwd = input('transpwd','');
        $valiParam = [
                'type'   => 2,// 用户类型：1供应商；2社群|用户
                'user'   => $this->user,
                'payfee' => $payfee,
                'channel' => $channel,
                'transpwd' => $transpwd
        ];
        // 支付验证
        if(valiPayment($valiParam)) return Json::json_send(valiPayment($valiParam));
        $param = [
            'good_id'   => $travel_id,
            'total_fee' => $payfee ,
            'title'     => "【".$travel['titles']."】活动定金",
            'channel'   => $channel,//"ALI_APP";
            'type'      => 4,//发布活动支付定金;
        ];
        $this->redirect(url('pay/index', $param));
    }

    // 签到二维码
    public function qrcode()
    {
        if(!$this->user) return Json::json_send(1);
        $travel_id = input('travel_id',0);
        $travel = TravelModel::field('id,qrcode')->where(['id'=>$travel_id])->find();
        if(!$travel) return Json::json_send(4);

        $travel_activities = Activity::alias('a')
                                    ->join('travel_activity ta','a.id=ta.activity_id')
                                    ->field('a.*,ta.begintime start,ta.endtime end')
                                    ->where(['ta.travel_id'=>$travel_id])->select();
        $categorys = [];
        $titles = [];
        foreach ($travel_activities as $tk => $tv) {
            array_push($categorys, Activity::getCategory($tv['category']));
            array_push($titles, $tv['name']);
        }
        $travel['categorys'] = implode('+',$categorys);
        $travel['titles']    = implode('+',$titles);
        return Json::json_send(0,'',$travel);
    }

    public function cancel()
    {
        if(!$this->user) return Json::json_send(1);
        $travel_id = input('travel_id',0);
        if(TravelModel::where(['id'=>$travel_id])->update(['state'=>5]))
        {
            // 活动取消   给报名活动的会员退款
            $list = model('TravelMember')->where(['travel_id'=>$travel_id])->select();
            foreach ($list as $k => $v) {
                $order = model('Order')->where(['type'=>1,'good_id'=>$v['id']])->find();
                //$this->redirect(url('pay/refund', ['order_id'=>$order['id']]));
                action('pay/refund', ['order_id'=>$order['id']]);
            }

            return Json::json_send(0);
        }
        return Json::json_send(9);
    }

    public function cancelsignup()
    {
        if(!$this->user) return Json::json_send(1);
        $travel_id = input('travel_id',0);
        if(Travel::where(['id'=>$travel_id])->update(['state'=>5]))
        {
            return Json::json_send(0);
        }
        return Json::json_send(9);
    }


    /*
    * 修改行程费用
    */
    public function expenses(Request $request)
    {
        if(!$this->user) return Json::json_send(1);
        $travel_id = input('travel_id',0);
 
        if($request->isPost())
        {
            $data = input();
            $travel = TravelModel::where(['id'=>$travel_id])->find();
            if(!$travel) return Json::json_send(4);
            if($travel['type'] == 1) $data['state'] = 2;

            if(model('Travel')->isUpdate(true)->allowField(true)->save($data,['id'=>$travel_id]))
            {
                model('TravelOther')->where(['travel_id'=>$data['travel_id']])->delete();
                if(input('others'))
                {
                    $list = [];
                    foreach (json_decode($data['others'],true) as $k => $v) {
                       $list[] = ['travel_id'=>$data['travel_id'],'name'=>$v['name'],'fee'=>$v['fee'],'notes'=>$v['notes']];
                    }
                    model('TravelOther')->isUpdate(false)->allowField(true)->saveAll($list);
                }
                return Json::json_send(0);
            }
            return Json::json_send(9);
        }

        $type = TravelModel::where(['id'=>$travel_id])->value('type');
        $join = $type==1?'oversea':'activity';
        $travel = TravelModel::with($join)->where(['id'=>$travel_id])->find();
        $other = model('TravelOther')->field('id as otherid,name,fee,notes')->where(['travel_id'=>$travel_id,'is_delete'=>0])->select();
        $data = [
            'id' => $travel_id,
            'total_fee' => $travel['total_fee'],
            'cost' => $travel['cost'],
            'group_num'=>$travel['group_num'] == 0 ? TravelModel::getTeamnum($travel['user_scale']):$travel['group_num'],
            'limit_num'=>$travel['limit_num'] == 0 ?TravelModel::getLimitnum($travel['user_scale']):$travel['limit_num'],
            'price'=>$travel['price'],
            'memebr_price'=>$travel['memebr_price'],
            'other'=>$other,
            'mode'=>$travel['mode'],
            'desc'=>$travel['desc'],
        ];
        return Json::json_send(0,'',$data);

    }

    public function other()
    {
        if(!$this->user) return Json::json_send(1);
        $to_id = input('otherid');
        if(model('TravelOther')->where('id',$to_id)->update(['is_delete'=>1]))
        {
            return Json::json_send(0);
        }
        return Json::json_send(9);
    }


    public function base($data)
    {
        if(model('Travel')->allowField(true)->save($data))
        {
            $qrcode = qrcode(model('Travel')->id,url('User/checkin',['travelid'=>model('Travel')->id])); 
            model('Travel')->isUpdate(true)->save(['qrcode'=>$qrcode,'id'=>model('Travel')->id]);
            return Json::json_send(0,'',['travel_id'=>model('Travel')->id]);
        }
    }

    public function chooseActivity($data)
    {
        $travel_id = $data['travel_id'];
        // 行程详情
        $travel = TravelModel::where(['id'=>$travel_id])->find();
        // 选择活动列表 
        $list = [];
        // 行程总费用
        $cost = 0;

        // 行程标题：选择的活动名称的拼接
        $titles = [];

        // 行程分类：选择的活动分类的拼接
        $categorys = [];
       
        // 根据活动类型查询不同的表
        $a_model = $travel['type']==1?model('Oversea'):model('Activity');

        // 遍历选择的活动id列表
        foreach(explode(',', $data['activity_ids']) as $k => $v){
            $activity = $a_model->where(['id'=>$v])->find();
            $cost += $activity['fee'];
            array_push($titles, $activity['name']);
            if($travel['type'] == 0)
            {
               array_push($categorys, Activity::getCategory($activity['category']));
            }
            $list[] = ['travel_id'=>$data['travel_id'],'activity_id'=>$v];
        }
        model('TravelActivity')->where(['travel_id'=>$travel_id])->delete();
        if(model('TravelActivity')->isUpdate(false)->allowField(true)->saveAll($list))
        {
            // 海外
            if($travel['type']==1)
            {
                $saveData['total_fee'] = $saveData['memebr_price'] = $saveData['cost'] = $saveData['price'] = $cost;
                $saveData['deposit'] = $cost * (config('signup_oversea_percent')/100);//海外活动支付订金
                $saveData['titles'] = implode('+',$titles);// 拼接活动名称
                $saveData['categorys'] = '海外游学';
                // 保存活动信息
                model('Travel')->isUpdate(true)->save($saveData,['id'=>$travel_id]);

                // 选择行程时间范围
                $choosetimeList = getDateRange($travel['begintime'],$travel['endtime']);
                // 查询该行程选择的所有活动
                $travel_activities = model('TravelActivity')->where(['travel_id'=>$travel_id])->select();

                // 行程开始时间
                $starttime = $travel['begintime'];
                // 遍历所有活动，安排时间
                foreach ($travel_activities as $k => $v) {
                    $endtime = $starttime + 8*3600;  
                    model('TravelActivity')->where(['travel_id'=>$travel_id,'activity_id'=>$v['activity_id']])->update(['begintime'=>$starttime,'endtime'=>$endtime]);
                    $starttime = $starttime+24*3600;
                }

                $travel_activities = Oversea::alias('a')
                            ->join('travel_activity ta','a.id=ta.activity_id')
                            ->field('a.*,ta.begintime start,ta.endtime end')
                            ->where(['ta.travel_id'=>$travel_id])->select();
                $data = [];
                foreach ($travel_activities as $k => $v) {
                    $data[] = [
                        'id'      => $v['id'],
                        'start'   => $v['start'],
                        'end'     => $v['end'],
                        'name'    => $v['name'],
                        'fee'     => $v['fee'],
                        'address' => $v['address'],
                        'longitude'   => $v['longitude'],
                        'latitude'    => $v['latitude'],
                    ];
                }
                return Json::json_send(0,'',$data);

            }
           $saveData['total_fee'] = $saveData['cost'] = $cost;
           $saveData['memebr_price'] = $saveData['price'] = $cost/TravelModel::getTeamnum($travel['user_scale']);
           $saveData['titles'] = implode('+',$titles);
           $saveData['categorys'] = implode('+',$categorys);
           model('Travel')->isUpdate(true)->save($saveData,['id'=>$travel_id]);
           $respData = [];
           $map['a.is_delete'] = '0';
           $map['s.type'] = '1';
           $siteList = Activity::alias('a')->field('a.id,a.poster,a.name,a.is_house,a.address,a.fee')->join('supplier s','s.id=a.supplier_id')->where($map)->select();

           $noSiteCount = model('TravelActivity')->alias('ta')->join('Activity a','ta.activity_id=a.id')->where(['ta.travel_id'=>$data['travel_id'],'a.is_site'=>0])->count();
           $respData['travel_id'] = $data['travel_id'];
           $respData['nositenum'] = $noSiteCount; 
           $respData['sitelist'] = $siteList; 
           return Json::json_send(0,'',$respData);
        }
    }

    public function chooseSite($travel_id,$activity_id,$site_id)
    {
        $result = model('TravelActivity')
                ->where(['travel_id'=>$travel_id,'activity_id'=>$activity_id])
                ->update(['site_id'=>$site_id]);
        if($result != false)
        {
            return Json::json_send(0);
        }
        return Json::json_send(9);
    }

    public function generateOverseas($travel_id)
    {
        $join = 'oversea';
        $travel = TravelModel::with($join)->where(['id'=>$travel_id])->find();
        $choosetimeList = getDateRange($travel['begintime'],$travel['endtime']);
        $titles = [];
        foreach ($travel[$join] as $k => $v) {
            array_push($titles, $v['name']);
        }

        $begintime = 0;
        foreach ($travel[$join] as $k => $v) {
            $starttime =empty($begintime)?$travel['begintime']:$begintime;
            $endtime = $starttime+($v['time']-1)*24*3600;   
            $result = model('TravelActivity')->where(['travel_id'=>$travel_id,'activity_id'=>$v['pivot']['activity_id']])->update(['begintime'=>$starttime,'endtime'=>$endtime]);
            $begintime = $endtime+24*3600; 
        }

        $url = config('url_domain_root').url('travel/info',['travel_id'=>$travel_id]);
        $return = [
            'travel_id' => $travel_id,
            'url'       => $url,
        ];
        return Json::json_send(0,'',$return);
    }

    public function generateTravel($travel_id){
       /* $type = TravelModel::where(['id'=>$travel_id])->value('type');
        $join = $type==1?'oversea':'activity';*/
        $join = 'activity';
        $travel = TravelModel::with($join)->where(['id'=>$travel_id])->find();
        if(!$travel) return Json::json_send(4);
        $choosetimeList = getDateRange($travel['begintime'],$travel['endtime']);
        $titles = [];
        foreach ($travel[$join] as $k => $v) {
            array_push($titles, $v['name']);
        }
        $thisselected = [];
        foreach ($travel[$join] as $k => $v) {
            // 活动已经被选择的日期（按整天计算）
            $selected = Collection(ActivityCalendar::where(['is_delete'=>0,'activity_id'=>$v['pivot']['activity_id']])->column('time'))->toArray();
            if($v['pivot']['site_id'])
            {
                $v['begintime'] = Activity::where('id',$v['pivot']['site_id'])->value('begintime');
                // 场地被选择的日期（按整天计算）
                $siteselected = Collection(ActivityCalendar::where(['is_delete'=>0,'activity_id'=>$v['pivot']['site_id']])->column('time'))->toArray();
                $selected = array_keys(array_flip($selected)+array_flip($siteselected));
            }
            // 行程时间段内该活动的空余时间
            $lasttime =array_diff(array_diff($choosetimeList,$selected),$thisselected);
            array_push($thisselected, reset($lasttime));
            $starttime = strtotime(date('Y-m-d',reset($lasttime)).' '.Activity::getBeginTime($v['begintime']));
            $endtime = strtotime(date('Y-m-d',reset($lasttime)).' '.Activity::getBeginTime($v['begintime']))+$v['time']*3600;   
            $result = model('TravelActivity')->where(['travel_id'=>$travel_id,'activity_id'=>$v['pivot']['activity_id']])->update(['begintime'=>$starttime,'endtime'=>$endtime]);
            if($result !== false)
            {
                $acdata = [
                    'activity_id'=> $v['id'],
                    'time'       => reset($lasttime),
                    'remark'     => implode('+',$titles),
                ];
                model('ActivityCalendar')->insert($acdata);
            }
        }

        $url = config('url_domain_root').url('travel/info',['travel_id'=>$travel_id]);
        $return = [
            'travel_id' => $travel_id,
            'url'       => $url,
        ];
        // 转移到定金支付完成后给予推送
        /*foreach ($travel[$join] as $k => $v) {
            $sponsor = model('User')->get(['id'=>$travel['sponsor']]);
            jpush(1,$sponsor['mobile'],$v['name'].'发布了活动');
        }*/
        
        return Json::json_send(0,'',$return);
        /*$data = [];
        foreach ($travel[$join] as $k => $v) {
            $data[] = [
                'id'     => $v['id'],
                'start'  => $v['pivot']['begintime'],
                'end'    => $v['pivot']['endtime'],
                'name'   => $v['name'],
                'address'=> $v['address']
            ];
            if($type==0){
                $data[$k]['category']=$v['category'];
            }
        }
        return Json::json_send(0,'',$data);*/
    }

     // h5 行程详情
    public function info()
    {
        $travel_id = input('travel_id',0);
        $is_signup = input('is_signup',0);
        $this->view->assign('is_signup',$is_signup);

        $diy = TravelModel::where(['id'=>$travel_id])->value('diy');
        // DIY 活动
        if($diy)
        {
            $info = TravelModel::where(['id'=>$travel_id])->find();
            if($info['diy_desc'])
            {
                $arr = json_decode($info['diy_desc'],true);
                $text = $arr['text'];
                $length = 0;
                foreach ($arr['img'] as $k => $v)
                {
                    $img = '<img src="'.stripslashes($v['body']).'" class="img marginT15" />';
                    $text = afterStr($text,$v['position']+$length,$img);
                    $length += strlen($img);
                }
                $info['diy_desc']  = $text;
            }

            $this->view->assign('info',$info);
            return $this->view->fetch('travel/diy');// DIY活动
        }


        $type = TravelModel::where(['id'=>$travel_id])->value('type');

        $join = $type==1?'oversea':'activity';

        $travel = TravelModel::with($join)->where(['id'=>$travel_id])->find();

        $data = [];
        $maps = [];
        $travelOthers = model('TravelOther')->field('id otherid,name,fee,notes')->where(['is_delete'=>0,'travel_id'=>$travel_id])->select();
        $data = [];
        $destinations = [];
        foreach ($travel[$join] as $k => $v) {
            $destinations[$k] = $v['latitude'].','.$v['longitude'];
            if(count($travel[$join]) == ($k+1))
            {
                $destinations[$k+1] = $v['latitude'].','.$v['longitude'];
            }
        } 
        $start = 1;
        foreach ($travel[$join] as $k => $v) {
            $date = $type==1?date('Y.m.d',$v['pivot']['begintime']).'-'.date('Y.m.d',$v['pivot']['endtime']):date('Y/m/d',$v['pivot']['begintime']);
            $v['category_abbr'] = '海';
            $v['distance']      = getNextDistance($v['latitude'].','.$v['longitude'],$destinations[$k+1]);
            if($type == 0)
            {
                $v['category_abbr'] = model('Activity')->getAcCategoryAbbr($v['category']);
                if(!$v['is_site']){
                    $site_id = model('TravelActivity')->where(['travel_id'=>$travel_id,'activity_id'=>$v['id']])->value('site_id');
                    $siteinfo = model('Activity')->get($site_id);
                    $v['address'] = $siteinfo['address'];
                    $v['longitude'] = $siteinfo['longitude'];
                    $v['latitude'] = $siteinfo['latitude'];
                }
                if(isset($v['plan']) && $v['plan'])
                {
                    $v['plan'] = json_decode($v['plan'],true);
                }

                if(isset($v['desc']) && $v['desc'])
                {
                    $arr = json_decode($v['desc'],true);
                    $text = $arr['text'];
                    $length = 0;
                    foreach ($arr['img'] as $ak => $av)
                    {
                        $img = '<img src="'.$av['body'].'" class="img marginT15" />';
                        $text = afterStr($text,$av['position']+$length,$img);
                        $length += strlen($img);
                    }
                    $v['desc']  = $text;
                }
            }
            if($type == 1)
            {
                $data['schedule'][$date]['days']  = $start ."-".($start+$v['time']-1);
            }

            $start = $start+$v['time'];
            
            $data['schedule'][$date]['activties'][$v['id']] = $v;
            $maps[$k] =  [
                'lon' => $v['longitude'],
                'lat' => $v['latitude']
            ];
        } 
        $data['other'] = $travelOthers;
        $data['memebr_price'] = $travel['memebr_price'];
        $data['desc'] = $travel['desc'];

        $signuplist = TravelMember::alias('tm')->join('user u','tm.member_id=u.id')
                ->field('u.id,u.avatar,u.name,u.state,u.mobile,tm.is_checkin,tm.check_time,tm.paid,tm.paid_fee')
                ->where(['travel_id'=>$travel_id])
                ->order('check_time desc')
                ->select();
        foreach ($signuplist as $k => $v) {
             $signuplist[$k]['mobile'] = substr_replace($v['mobile'],'****',0,7);
        }
        $data['signuplist'] = $signuplist;
        //return Json::json_send(0,'',$data);
        $this->view->assign('maps',json_encode($maps));
        $this->view->assign('travel',$data);
        $this->view->assign('type',$type);
        $this->view->assign('parentid',input('parentid',0));
        if($type==1)
        {
            return $this->view->fetch('travel/oinfo');// 活动商
        }
        return $this->view->fetch('travel/info');// 活动商
    }
}
